package classign.election.kingvar.come.electionclasssign.module.main.punchcard;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import classign.election.kingvar.come.electionclasssign.R;
import classign.election.kingvar.come.electionclasssign.activity.MyApplication;
import classign.election.kingvar.come.electionclasssign.adapter.RecyclerAdapter;
import classign.election.kingvar.come.electionclasssign.adapter.RecyclerViewHolder;
import classign.election.kingvar.come.electionclasssign.api.info.ProMessageContent;
import classign.election.kingvar.come.electionclasssign.base.BaseProtocol;
import classign.election.kingvar.come.electionclasssign.greendao.MemberClock;
import classign.election.kingvar.come.electionclasssign.greendao.MemberClockDao;
import classign.election.kingvar.come.electionclasssign.greendao.StudentInfo;
import classign.election.kingvar.come.electionclasssign.greendao.StudentInfoDao;
import classign.election.kingvar.come.electionclasssign.injector.components.DaggerPunchCardComponent;
import classign.election.kingvar.come.electionclasssign.injector.modules.PunchCardModule;
import classign.election.kingvar.come.electionclasssign.interfaces.OnCardSlotListener;
import classign.election.kingvar.come.electionclasssign.module.base.BaseActivity;
import classign.election.kingvar.come.electionclasssign.tools.bean.ActivityStatusBean;
import classign.election.kingvar.come.electionclasssign.tools.bean.User;
import classign.election.kingvar.come.electionclasssign.tools.utils.DateUtil;
import classign.election.kingvar.come.electionclasssign.tools.utils.NetUtil;
import classign.election.kingvar.come.electionclasssign.tools.utils.ToastUtils;
import classign.election.kingvar.come.electionclasssign.tools.utils.TypeFaceUtil;
import classign.election.kingvar.come.electionclasssign.tools.views.CircleImageView;
import classign.election.kingvar.come.electionclasssign.tools.views.DividerGridItemDecoration;
import classign.election.kingvar.come.electionclasssign.tools.views.DividerItemDecoration;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;

/**
 * 刷卡模式界面
 * Created by JYQ on 2017/1/10 0010.
 */
public class PunchCardActivity extends BaseActivity<PunchCardPresenter> implements IPunchCardView, View.OnClickListener {
    private static final String TAG = "PunchCardActivity";
    private RecyclerAdapter mRecyclerAdapter;
    @BindView(R.id.rv_punch_card)
    RecyclerView rv_punch_card; //学生的recycleview
    @BindView(R.id.rv_time_table)
    RecyclerView mRvTimeTable;
    @BindView(R.id.iv_head_picture)
    ImageView iv_head_picture;  //头像
    @BindView(R.id.tv_student_name)
    TextView tv_student_name; //名字
    @BindView(R.id.tv_class_name)
    TextView tv_class_name;  //班级名字
    @BindView(R.id.tv_class_leader_one)
    TextView tv_class_leader_one;  //班主任
    @BindView(R.id.tv_job_one)
    TextView tv_job_one;  //当任职务
    @BindView(R.id.tv_job_two)
    TextView tv_job_two;  //校职务
    @BindView(R.id.tv_motto_content)
    TextView tv_motto_content;  //座右铭
    @BindView(R.id.rv_message_board)
    RecyclerView mRvMessageBoard;  //留言板 列表
    @BindView(R.id.edt_comment)
    EditText edt_comment;  //留言 编辑框
    @BindView(R.id.iv_head_pic)
    CircleImageView iv_head_pic;  //留言小头像
    private StudentInfoDao mStudentInfoDao;
    private String card_id = "";  //卡的id
    private List<StudentInfo> list;
    private List<StudentInfo> list_all;
    private OnCardSlotListener listner;

    int column = 3;  //班级有 列
    private MemberClockDao memberClockDao;  //已经打卡的数据表
    private long dakaTime;  //打卡的时间
    private MemberClock memberClock;
    private ProgressDialog pd;
    private List<ProMessageContent.DataEntity> entityList;//留言板数据的集合
    private List<ProMessageContent.TListEntity> tListEntityList;//留言板数据的集合

    private int messagetID; // 点击留言的人的id
    private int studentId;  //刷卡的学生的id

    private RecyclerAdapter mRecyclerAdapter1;  //留言板 adapter
    private RecyclerAdapter<ProMessageContent.TListEntity> mTimeRecyclerAdapter;  //时间表 adapter
    private Subscription subscription;


    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_punch_card;
    }

    @Override
    protected void initInjector() {
        new ActivityStatusBean().setStatus(true);
        DaggerPunchCardComponent.builder().applicationComponent(getAppComponent())
                .punchCardModule(new PunchCardModule(this)).build().inject(this);
    }

    @Override
    protected void initViews() {
        mRvMessageBoard.setLayoutManager(new LinearLayoutManager(this));
        mRvMessageBoard.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.HORIZONTAL));

        mRvTimeTable.setLayoutManager(new GridLayoutManager(this, 5));
        mRvTimeTable.addItemDecoration(new DividerGridItemDecoration(this));
        card_id = getIntent().getStringExtra("registerID");
        mStudentInfoDao = MyApplication.getAppComponent().getDaoSession().getStudentInfoDao();
        memberClockDao = MyApplication.getAppComponent().getDaoSession().getMemberClockDao();
        tv_class_leader_one.setText("班主任 :" + User.getClassTeacherOne(this));
        tv_class_name.setText(User.getClassName(this));
        tv_motto_content.setTypeface(TypeFaceUtil.initTypeface(this));//设置字体
        list_all = mStudentInfoDao.loadAll();
        searchDb();
        int column = getStudentColumn();
        rv_punch_card.setLayoutManager(new GridLayoutManager(this, column));


    }

    @Override
    protected void updateViews(boolean isRefresh) {
        creatAdapter();
        checkDakaInfo();
    }


    /**
     * 上传数据 到服务器
     */
    private void updateData() {

        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pd.setTitle("温馨提示");
        pd.setMessage("数据上传中，请稍后刷卡...");
        pd.setCancelable(false);
        pd.show();
        List<MemberClock> memberClocks = memberClockDao.loadAll();
        mPresenter.postUpLoadData(User.getImei(this), User.getSchoolId(this)
                , DateUtil.getDateY(System.currentTimeMillis() + ""), new Gson().toJson(memberClocks));


    }

    private void creatAdapter() {
        Log.i(TAG, "handleMessage: szie = " + list_all.size());
        if (mRecyclerAdapter == null) {
            mRecyclerAdapter = new RecyclerAdapter<StudentInfo>(R.layout.item_punch_card, list_all) {
                @Override
                protected void onBindData(RecyclerViewHolder holder, int position, StudentInfo item) {
                    TextView tv_punch_card = holder.findViewById(R.id.tv_punch_card);
                    if (list_all.get(position).getTag() == 0) {
                        tv_punch_card.setTextColor(Color.BLACK);
                    } else if (list_all.get(position).getTag() == 1) {
                        tv_punch_card.setTextColor(Color.WHITE);
                    }
                    holder.setText(R.id.tv_punch_card, list_all.get(position).getName());
                    mRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            edt_comment.setText("");
                            edt_comment.setHint("给" + list_all.get(position).getName() + "的留言:");
                            edt_comment.requestFocus();
                            messagetID = list_all.get(position).getStudentid();
                        }
                    });

                }

            };
            rv_punch_card.setAdapter(mRecyclerAdapter);
        } else {
            mRecyclerAdapter.setItemDate(list_all);
        }
    }

    /**
     * 开线程 2分钟上传一次 数据
     */
    private void checkDakaInfo() {
        subscription = Observable.interval(2, 2, TimeUnit.MINUTES)
                .compose(this.bindToLife())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Long>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        updateData();
                    }
                });

    }

    /**
     * 获取 班级学生有几列
     *
     * @return
     */
    private int getStudentColumn() {
        if (list_all.size() > 27 && list_all.size() <= 36) {
            column = 4;
        } else if (list_all.size() > 36 && list_all.size() <= 45) {
            column = 5;
        } else if (list_all.size() > 45 && list_all.size() <= 54) {
            column = 6;
        } else if (list_all.size() > 54 && list_all.size() <= 63) {
            column = 7;
        } else if (list_all.size() > 63 && list_all.size() <= 72) {
            column = 8;
        } else if (list_all.size() <= 27) {
            column = 3;
        }
        return column;
    }

    /**
     * 通过卡的id 查询数据库
     */
    private void searchDb() {
        list = mStudentInfoDao.queryBuilder().where(StudentInfoDao.Properties.RegisterID.eq(card_id)).build().list();
        card_id = "";
        Log.i(TAG, "initData: aa = " + list.size());
        edt_comment.clearFocus();

        if (list.size() > 0) {
            StudentInfo studentInfo = list.get(0);
            Log.i(TAG, "searchDb: studentinfo = " + studentInfo);
            Log.i(TAG, "searchDb:index " + list_all.indexOf(studentInfo));
            tv_job_one.setText("当任职务 :" + studentInfo.getDuty());
            tv_job_two.setText("校职务 :" + studentInfo.getSchoolDuty());
            tv_motto_content.setText(studentInfo.getMemo());
            tv_student_name.setText(studentInfo.getName());
            Glide.with(this).load(BaseProtocol.IMG_BASE + studentInfo.getLogo())
                    .error(R.drawable.miyue).into(iv_head_picture);
            Glide.with(this).load(BaseProtocol.IMG_BASE + studentInfo.getLogo())
                    .error(R.drawable.miyue).into(iv_head_pic);
//            Log.i(TAG, "dispatchKeyEvent: tag = " + list_all.get(list_all.indexOf(studentInfo)).getTag());
            dakaTime = System.currentTimeMillis();
            memberClock = new MemberClock(null, 2, studentInfo.getStudentid(), dakaTime);
            List<MemberClock> memberClocks = memberClockDao.loadAll();
            mPresenter.getMessageContent(studentInfo.getStudentid());
            studentId = studentInfo.getStudentid();
            if (memberClocks != null && memberClocks.size() > 0 && memberClocks.contains(memberClock)
                    && memberClock.getTime() - memberClocks.get(memberClocks.lastIndexOf(memberClock)).getTime() < 2 * 60 * 1000L) {
                ToastUtils.showToast("请勿重复刷卡");
                edt_comment.clearFocus();
                creatAdapter();

                return;
            } else {
                list_all.get(list_all.indexOf(studentInfo)).setTag(1);
                ToastUtils.showToast("打卡成功");
                edt_comment.clearFocus();
                creatAdapter();

            }
            memberClockDao.insert(memberClock);
        } else {
            ToastUtils.showToast("卡号未绑定或者不是本班级学生");
        }
    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
//        Log.i(TAG, "dispatchKeyEvent: event.getAction()= " +event.getAction() );
        if (event.getAction() == KeyEvent.ACTION_UP) {
            return true;
        } else if (KeyEvent.KEYCODE_ENTER == event.getKeyCode()) {

            if (listner != null) {
                listner.onCardSlot(card_id);
            }
            searchDb();

            return true;
        }
        String str = String.valueOf((char) event.getUnicodeChar());
        if (!TextUtils.isEmpty(str)) {
            card_id += str;
            return true;
        }
        return true;
    }

    @Override
    public void loadMessageData(List<ProMessageContent.DataEntity> dataEntities) {
        entityList = dataEntities;
        if (entityList.size() == 0) {
            ToastUtils.showToast("暂时还没有留言呦!");
        }
        if (mRecyclerAdapter1 == null) {
            mRecyclerAdapter1 = new RecyclerAdapter<ProMessageContent.DataEntity>(R.layout.item_message_board, entityList) {
                @Override
                protected void onBindData(RecyclerViewHolder holder, int position, ProMessageContent.DataEntity item) {
                    holder.setText(R.id.tv_comment, item.getContent());
                    holder.setText(R.id.tv_time, DateUtil.getDate(item.getTime() + ""));
                    holder.setText(R.id.tv_name, item.getName());
                    Glide.with(PunchCardActivity.this).load(BaseProtocol.IMG_BASE + item.getLogo())
                            .error(R.drawable.miyue).into((ImageView) holder.getItemView().findViewById(R.id.iv_circle_pic));
                }
            };
            mRvMessageBoard.setAdapter(mRecyclerAdapter1);
        } else {
            mRecyclerAdapter1.setItemDate(entityList);
        }
    }

    @Override
    public void loadTimeTableData(List<ProMessageContent.TListEntity> tList) {
        Log.i(TAG, "loadTimeTableData: size= " + tList.size());
        Log.i(TAG, "loadTimeTableData: list= " + tList);
        tListEntityList = tList;
        if (mTimeRecyclerAdapter == null) {
            mTimeRecyclerAdapter = new RecyclerAdapter<ProMessageContent.TListEntity>(R.layout.item_time_table, tListEntityList) {
                @Override
                protected void onBindData(RecyclerViewHolder holder, int position, ProMessageContent.TListEntity item) {
                    TextView tv_time_of_table = (TextView) holder.getItemView().findViewById(R.id.tv_time_of_table);
                    if (tListEntityList.get(position).getTime() == 0) {
                        tv_time_of_table.setText("");
                    } else {
                        tv_time_of_table.setText(DateUtil.getDate(item.getTime() + ""));
                    }

                }
            };
            mRvTimeTable.setAdapter(mTimeRecyclerAdapter);
        } else {
            mTimeRecyclerAdapter.setItemDate(tListEntityList);
        }
    }

    @Override
    public void sendMessageSuccess() {
        ToastUtils.showToast("留言成功");
        edt_comment.setText("");
        edt_comment.clearFocus();
    }

    @Override
    public void postUploadDataFail() {
        if (NetUtil.getNetWorkState(this) != NetUtil.NETWORK_NONE) {
            mPresenter.postUpLoadData(User.getImei(this), User.getSchoolId(this)
                    , DateUtil.getDateY(System.currentTimeMillis() + ""), new Gson().toJson(memberClockDao.loadAll()));
        } else {
            pd.dismiss();
        }
        ToastUtils.showToast("数据上传失败");
        pd = null;
        finish();

    }

    @Override
    public void postUploadDataSuccess() {
        ToastUtils.showToast("数据上传成功");
        pd.dismiss();
        pd = null;
        memberClockDao.deleteAll();
        finish();
    }


    @OnClick({R.id.iv_close_btn, R.id.btn_send})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close_btn:
                finish();
                new ActivityStatusBean().setStatus(false);
                break;
            case R.id.btn_send:
                if (edt_comment.getText().toString().isEmpty()) {
                    ToastUtils.showToast("请输入留言内容");
                    return;
                }
                if (studentId == messagetID || messagetID == 0) {
                    ToastUtils.showToast("不能给自己留言");
                    edt_comment.setText("");
                    return;
                }
                mPresenter.sendMessageContent(studentId, messagetID, edt_comment.getText().toString());
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (subscription != null) {
            subscription.unsubscribe();
        }
        new ActivityStatusBean().setStatus(false);
        super.onDestroy();
    }


}
